package com.mediacloud.app.newsmodule.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mediacloud.app.assembly.views.NetImageViewX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.share.model.ShareGridItem;
import com.mediacloud.app.share.utils.ShareGridDataUtil;
import com.mediacloud.app.share.view.BadgeView;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

@SuppressWarnings("ALL")
public class ShareComponent extends LinearLayout implements AdapterView.OnItemClickListener {
    private String TAG = getClass().getSimpleName();
    private String mShareTarget = "- 分享到 -";
    private Context mContext;
    private View sharePlatforms;
    private GridView shareGrid;
    private GridAdaptor adaptor;
    private int mHeadTextColor = Color.BLACK;
    private float mHeadTextSize = 28;
    private TextView tv_top;
    private int defaultCloums = 4;
    private ItemClickInfoListener itemClickInfoListener;
    private LinearLayout llcontainer;
    public static final int TOP_TYPE_NONE = 3;
    public static final int TOP_TYPE_TEXT = 1;
    public static final int TOP_TYPE_IMAGE = 2;
    public static final int TOP_LOCATION_LEFT = 2;
    public static final int TOP_LOCATION_CENTER = 1;
    private int mTopType = TOP_TYPE_NONE;
    private int mTopLocation = TOP_LOCATION_CENTER;
    private String mImageUrl = "";

    public ShareComponent(Context context) {
        super(context);
        init(context, null, 0, 0);
    }

    public ShareComponent(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0, 0);
    }

    public ShareComponent(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr, 0);
    }


    private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        mContext = context;
        setOrientation(VERTICAL);
        setBackgroundColor(Color.TRANSPARENT);
        setPadding(0, 20, 0, 20);
        mHeadTextSize = 16;//sp
        adaptor = new GridAdaptor();
        addTopContainer();
    }

    private void addTopContainer() {
        llcontainer = new LinearLayout(mContext);
//        llcontainer.setOrientation(VERTICAL);
        llcontainer.setPadding(dpToPx(15, mContext), 0, dpToPx(15, mContext), 0);
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.topMargin = dpToPx(10,mContext);
        params.bottomMargin = dpToPx(10,mContext);
        llcontainer.setLayoutParams(params);
        addView(llcontainer);
    }


    public void addTopContent() {
        //set gravity
        if (llcontainer != null) {
            if (mTopLocation == TOP_LOCATION_CENTER) {
                llcontainer.setGravity(Gravity.CENTER_HORIZONTAL);
            } else if (mTopLocation == TOP_LOCATION_LEFT){
                llcontainer.setGravity(Gravity.LEFT);
            }
        }
        switch (mTopType) {
            case TOP_TYPE_NONE:
                //add nothing
                break;
            case TOP_TYPE_TEXT:
                addHeadText();
                break;
            case TOP_TYPE_IMAGE:
                addHeadImage();
                break;
        }
    }

    public int dpToPx(float dpValue, Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public int px2DP(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        Log.i(TAG, "onMeasure : measuredWidth " + measuredWidth + " measuredHeight : " + measuredHeight);


    }


    private void addHeadText() {
        if (llcontainer == null) {
            return;
        }
        if (mTopType != TOP_TYPE_TEXT) {
            return;
        }
        tv_top = new TextView(mContext);
        tv_top.setTextColor(mHeadTextColor);
        tv_top.setText(mShareTarget);
        tv_top.setTextSize(mHeadTextSize);
        TextPaint paint = tv_top.getPaint();
//        paint.setFakeBoldText(true);
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
//                LayoutParams.WRAP_CONTENT);
//        tv_top.setLayoutParams(lp);
        llcontainer.addView(tv_top);
    }

    private void addHeadImage() {
        if (llcontainer == null || TextUtils.isEmpty(mImageUrl)) {
            return;
        }
        NetImageViewX imageView = new NetImageViewX(mContext);
        float oldD = mContext.getResources().getDimension(R.dimen.dimen43);
//        float oldD = dpToPx(43,mContext);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                (int) oldD
        );
        imageView.setLayoutParams(layoutParams);
        imageView.defaultBackGroundColor = 0xFF888888;
//        imageView.defaultDrawable=AppFactoryGlobalConfig.getDefaultImageLoadDrawable();
        imageView.setDefaultRes();
        //AppFactoryGlobalConfig.getAppServerConfigInfo(this).getHost()+
        imageView.load(mImageUrl);
        llcontainer.addView(imageView);
    }


    public ShareComponent setTargetText(String text) {
        mShareTarget = text;
        return this;
    }

    public ShareComponent setTopType(int type) {
        mTopType = type;
        return this;
    }

    public ShareComponent setTopLocation(int location) {
        mTopLocation = location;
        return this;
    }

    public ShareComponent setTargetTextSize(int textSize) {
        mHeadTextSize = textSize;
        return this;
    }


    private void addBottom() {
        sharePlatforms = LayoutInflater.from(mContext).inflate(R.layout.detailcomponent_gridstyle_share, null);
        sharePlatforms.setBackgroundColor(Color.TRANSPARENT);
        sharePlatforms.setPadding(0, 0, 0, 0);

        float dimension = getResources().getDimension(R.dimen.sharegrid_columnwidth);
        float pdtop = getResources().getDimension(R.dimen.sharegrid_columntxt_pdtop);
        List<ShareGridItem> gridItemList = adaptor.gridItemList;
        int size = gridItemList.size();
        int col = 0;
        if (size != 0) {
            col = size / defaultCloums + 1;
        } else {
            return;
        }
        float abHeight = (dimension + pdtop) * col + dpToPx(5, mContext);
        shareGrid = sharePlatforms.findViewById(R.id.shareGrid);
        shareGrid.setBackgroundColor(Color.TRANSPARENT);
        shareGrid.setNumColumns(defaultCloums);
        shareGrid.setAdapter(adaptor);
        shareGrid.setFocusable(false);
        sharePlatforms.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                boolean b = sharePlatforms.onTouchEvent(event);
                return b;
            }
        });
        //		shareGrid.setOnItemClickListener(gridListener);
        shareGrid.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    for (int i = 0; i < shareGrid.getChildCount(); i++) {
                        View view = shareGrid.getChildAt(i);
                        Rect rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
                        if (rect.contains((int) event.getX(), (int) event.getY())) {
                            onItemClick(shareGrid, view, i, i);
                            break;
                        }
                    }
                }
                return false;
            }
        });

        addView(sharePlatforms, LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);// (int) abHeight);
    }

    public ShareComponent setTargetImageUrl(String url) {
        mImageUrl = url;
        return this;
    }

    public ShareComponent build() {
        lazyAdd();
        return this;
    }

    private void lazyAdd() {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                addTopContent();
                addBottom();
            }
        }, 200);
    }


    protected class GridAdaptor extends BaseAdapter {

        public List<ShareGridItem> gridItemList = null;

        @Override
        public int getCount() {
            return gridItemList == null ? 0 : gridItemList.size();
        }

        @Override
        public ShareGridItem getItem(int position) {
            return gridItemList == null ? null : gridItemList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.sharegrid_itemmodule, null);
                holder = new ViewHolder();
                holder.shareGridItemImg = convertView.findViewById(R.id.shareGridItemImg);
                holder.shareGirdItemTxt = convertView.findViewById(R.id.shareGirdItemTxt);
                holder.badgeView = new com.mediacloud.app.share.view.BadgeView(mContext);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.shareGridItemImg.setImageResource(getItem(position).resId);

            holder.shareGirdItemTxt.setText(getItem(position).label);
            return convertView;
        }

        class ViewHolder {
            ImageView shareGridItemImg;
            TextView shareGirdItemTxt;
            BadgeView badgeView;
        }

    }


    public ShareComponent setShareGridAdaptorData(List<ShareGridItem> data) {
        if (adaptor != null) {
            adaptor.gridItemList = data;
        }
        return this;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
        if (itemClickInfoListener != null && adaptor != null) {
            itemClickInfoListener.onItemClicked(parent, view, position, id, adaptor.gridItemList.get(position));
        }
    }

    /**
     * 处理分享的注解
     */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AdapterViewItemClicked {

    }


    public interface ItemClickInfoListener {
        void onItemClicked(AdapterView<?> parent, View view, int position, long id, ShareGridItem item);
    }

    public ShareComponent setOnItemClickInfoListener(ItemClickInfoListener listener) {
        this.itemClickInfoListener = listener;
        return this;
    }
}